/********************************************************************************
 *@description:  宠圈举报
 *@author: Xhd
 *@API: 高贤亮
 *@date: 2024-04-19 14:25:12
 *@version: V1.0.0
**********************************************************************************/

import React, { Component } from 'react';
import { Modal, Tabs, Image, Badge, Input, Form, Tooltip } from 'antd';
import TheQueryForm from '@/components/TheQueryForm';
import TheTable from '@/components/TheTable';
import ThePagination from '@/components/ThePagination';
import TheButton from '@/components/TheButton';
import TheImage from '@/components/TheImage';
import VideoPlayer from "@/components/VideoPlayer";
import { apiDynamicReportPage, apiDynamicReportCheckAudit, apiDynamicReportAudit } from "@/request/pet";
import moment from 'moment';
import _ from "lodash";

class DynamicReport extends Component {
  constructor(props) {
    super(props)
    this.queryFormRef = React.createRef();
    this.processedFormRef = React.createRef();
    this.state = {
      searchOption: [
        {
          field: 'reportMemberLike',
          label: '举报人',
          placeholder: '输入会员ID/会员昵称/会员手机号',
          required: false,
          type: 'Input',
          defaultValue: '',
        },
        {
          field: 'dynamicMemberLike',
          label: '被举报人',
          placeholder: '输入会员ID/会员昵称/会员手机号',
          required: false,
          type: 'Input',
          defaultValue: '',
        },
        {
          field: "time",
          label: "举报时间",
          placeholder: "",
          required: false,
          rules: [],
          type: "RangePicker",
          defaultValue: "",
        },
        {
          field: 'dynamicId',
          label: '动态ID',
          placeholder: '请输入动态ID',
          required: false,
          type: 'Input',
          defaultValue: '',
        },
        {
          field: 'dynamicTitle',
          label: '动态标题',
          placeholder: '请输入动态标题',
          required: false,
          type: 'Input',
          defaultValue: '',
        },
        {
          field: "reportState",
          label: "举报状态",
          placeholder: "",
          required: false,
          rules: [],
          type: "Select",
          options: [
            { value: "", label: "全部" },
            { value: "0", label: "待审核" },
            { value: "1", label: "已处理" },
            { value: "2", label: "不处理" },
          ],
          defaultValue: "",
        },
      ],
      columns: [
        {
          title: "举报ID",
          dataIndex: "dynamicReportId",
          key: "dynamicReportId",
        },
        {
          title: "举报人",
          dataIndex: "reportMember",
          key: "reportMember",
          render: (text, record) => {
            return <div style={{ textAlign: 'left' }} >
              昵称：{record.reportMemberNickname}<br />
              ID：{record.reportMemberId}
            </div>
          }
        },
        {
          title: "被举报动态",
          dataIndex: "dynamic",
          key: "dynamic",
          render: (text, record) => (
            <div style={{ textAlign: 'left', maxWidth: "250px", overflow: 'hidden', whiteSpace: "nowrap", textOverflow: 'ellipsis' }} >
              动态ID：{record.dynamicId}<br />
              <Tooltip placement="topLeft" title={record.dynamicTitle}>标题：{record.dynamicTitle}</Tooltip><br />
              <Tooltip placement="topLeft" title={record.dynamicContent}>内容详情：{record.dynamicContent}</Tooltip>
            </div>
          )
        },
        {
          title: "动态媒体",
          dataIndex: "dynamicMedia",
          key: "dynamicMedia",
          render: (text, record) => {
            let dynamicMedia = JSON.parse(text)
            return <>
              {record.dynamicType === "1" ?
                <Image.PreviewGroup>
                  {dynamicMedia.image.map(value => {
                    return <TheImage src={value.url} width={80} height={80} />;
                  })}
                </Image.PreviewGroup>
                :
                dynamicMedia.video.map(value => {
                  return <TheImage preview={{ visible: false }}
                    src={value.url + "?x-oss-process=video/snapshot,t_1000,m_fast"}
                    width={80} height={80} onClick={() => {
                      this.videoDialog(value.url)
                    }} />;
                })
              }
            </>
          }
        },
        {
          title: "被举报人ID",
          dataIndex: "dynamicMember",
          key: "dynamicMember",
          render: (text, record) => {
            return <div style={{ textAlign: 'left' }} >
              昵称：{record.dynamicMemberNickname}<br />
              ID：{record.dynamicMemberId}<br />
              手机号：{record.dynamicMemberPhone}
            </div>
          }
        },
        {
          title: "举报原因",
          dataIndex: "reportType",
          key: "reportType",
        },
        {
          title: "证据图片",
          dataIndex: "reportEvidence",
          key: "reportEvidence",
          render: (text) => {
            let image = text.split(';')
            return <Image.PreviewGroup>
              {image.map(v => {
                return <TheImage src={v} width={80} height={80} />
              })}
            </Image.PreviewGroup>

          }
        },
        {
          title: "描述",
          dataIndex: "reportDescription",
          key: "reportDescription",
        },
        {
          title: "举报时间",
          dataIndex: "reportTime",
          key: "reportTime",
        },
        {
          title: "操作员",
          dataIndex: "processingUserName",
          key: "processingUserName",
        },
        {
          title: "处理状态",
          dataIndex: "reportState",
          key: "reportState",
          render: (text) => {
            let label = ''
            switch (text) {
              case "0":
                label = "待审核"
                break;
              case "1":
                label = "已处理"
                break;
              case "2":
                label = "不处理"
                break;
              default:
                break;
            }
            return label
          }
        },
        {
          title: "备注",
          dataIndex: "remark",
          key: "remark",
        },
        {
          title: "操作",
          dataIndex: "operate",
          key: "operate",
          fixed: "right",
          render: (text, record) => {
            return <div>
              <TheButton haspermi={['pet:report:notProcessed']} disabled={record.reportState !== "0"} onClick={() => this.Processed('0', record.dynamicReportId)} >不处理</TheButton>
              <TheButton haspermi={['pet:report:processed']} disabled={record.reportState !== "0"} onClick={() => this.Processed('1', record.dynamicReportId)} >去处理</TheButton>
            </div>
          }
        },
      ],
      dataSource1: [],
      dataSource2: [],
      pageData: { pageNo: 1, pageSize: 10 },
      total1: 0,
      total2: 0,
      queryForm: {},
      tabValue: "0",
      num: '',
      visible: false,
      title: '举报处理'
    }
  }

  componentDidMount() {
    this.getData()
    this.getReportData()
  }

  getData = async (values) => {
    const { pageData } = this.state
    if (values && !_.isEmpty(values.time)) {
      values.reportTimeStart = moment(values.time[0]).format("YYYY-MM-DD") + " 00:00:00";
      values.reportTimeEnd = moment(values.time[1]).format("YYYY-MM-DD") + " 23:59:59";
      delete (values.time)
    }
    await apiDynamicReportPage({ ...pageData, ...values }).then(res => {
      if (res.code === 0) {
        this.setState({
          dataSource1: res.data,
          total1: res.totalCount
        })
      }
    })
  }

  getReportData = async (values) => {
    const { pageData } = this.state
    if (values && !_.isEmpty(values.time)) {
      values.reportTimeStart = moment(values.time[0]).format("YYYY-MM-DD") + " 00:00:00";
      values.reportTimeEnd = moment(values.time[1]).format("YYYY-MM-DD") + " 23:59:59";
      delete (values.time)
    }
    await apiDynamicReportPage({ ...pageData, reportState: "0", ...values }).then(res => {
      if (res.code === 0) {
        this.setState({
          dataSource2: res.data,
          total2: res.totalCount,
          num: res.totalCount
        })
      }
    })
  }

  changeKey = (value) => {
    this.setState({
      tabValue: value
    })
    if (value === "0") {
      this.state.searchOption.push({
        field: "reportState",
        label: "举报状态",
        placeholder: "",
        required: false,
        rules: [],
        type: "Select",
        options: [
          { value: "", label: "全部" },
          { value: "0", label: "待审核" },
          { value: "1", label: "已处理" },
          { value: "2", label: "不处理" },
        ],
        defaultValue: "",
      },)
    } else {
      this.state.searchOption.pop()
    }
    this.queryFormRef.formRef.resetFields()
    this.onReset()
    // this.pageChange(1, 10)
  }

  videoDialog = (value) => {
    Modal.confirm({
      title: '视频预览',
      icon: "",
      content: <VideoPlayer src={value} />,
      cancelText: '关闭',
      width: "535px",
      maskClosable: true,
      closable: true,
      okButtonProps: { style: { display: "none" } },
      cancelButtonProps: { style: { display: "none" } },
    })
  }

  pageChange = (pageNo, pageSize) => {
    const { tabValue, queryForm } = this.state
    this.setState({
      pageData: {
        pageNo,
        pageSize
      }
    }, () => {
      if (tabValue === "0") {
        this.getData(queryForm)
      } else {
        this.getReportData(queryForm)
      }
    })
  }

  onFormSearch = (values) => {
    const { tabValue } = this.state
    this.setState({
      pageData: { pageNo: 1, pageSize: 10 }
    }, () => {
      this.setState({
        queryForm: { ...values }
      }, () => {
        if (tabValue === "0") {
          this.getData(values)
        } else {
          this.getReportData(values)
        }
      })
    })
  }

  onReset = () => {
    this.setState({
      queryForm: {},
    }, () => {
      this.pageChange(1, 10)
    })
  }

  Processed = async (processed, dynamicReportId) => {
    this.setState({
      processed,
      dynamicReportId
    })
    await apiDynamicReportCheckAudit({ dynamicReportId }).then(res => {
      if (res.code === 0) {
        this.setState({
          visible: true,
          title: res.data.code !== 0 ? '提示' : '举报处理',
          content: res.data.data
        })
      }
    })
  }

  ProcessedOk = async (processed, dynamicReportId) => {
    const { pageData } = this.state
    if (processed === '0') {
      console.log(this.processedFormRef);
      this.processedFormRef.validateFields().then(async (value) => {
        await apiDynamicReportAudit({ ...value, dynamicReportId, reportState: "2" }).then(res => {
          if (res.code === 0) {
            this.setState({ visible: false }, () => {
              this.pageChange(pageData.pageNo, pageData.pageSize)
            })
          }
        })
      });
    } else {
      await apiDynamicReportAudit({ dynamicReportId, reportState: "1" }).then(res => {
        if (res.code === 0) {
          this.setState({ visible: false }, () => {
            this.pageChange(pageData.pageNo, pageData.pageSize)
          })
        }
      })
    }
    console.log(processed, dynamicReportId);
  }

  render() {
    const { columns, dataSource1, dataSource2, pageData: { pageNo, pageSize }, total1, total2, searchOption, tabValue, num, visible, processed, dynamicReportId, content, title } = this.state;
    const tab = <Badge count={num}><div style={{ width: '70px' }}>待审核</div></Badge>
    return (<div className='p-layout-box'>
      <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={true} option={searchOption} onReset={() => this.onReset()} onGetValues={(values) => this.onFormSearch(values)} />
      <Tabs defaultActiveKey={tabValue} type='card' onChange={(v) => this.changeKey(v)} >
        <Tabs.TabPane key={"0"} tab="举报记录" >
          <TheTable scroll={{ x: 'max-content', y: '63vh' }} columns={columns} dataSource={dataSource1} />
          <ThePagination pageNo={pageNo} pageSize={pageSize} total={total1} pageChange={this.pageChange} />
        </Tabs.TabPane>
        <Tabs.TabPane key={"1"} tab={tab} >
          <TheTable scroll={{ x: 'max-content', y: '63vh' }} columns={columns} dataSource={dataSource2} />
          <ThePagination pageNo={pageNo} pageSize={pageSize} total={total2} pageChange={this.pageChange} />
        </Tabs.TabPane>
      </Tabs>
      <Modal open={visible} title={title}
        onCancel={() => this.setState({ visible: false })}
        okText={processed === '0' ? "确认" : "确认删除"}
        cancelText="取消"
        onOk={() => this.ProcessedOk(processed, dynamicReportId)}
        destroyOnClose
      >
        {processed === '0' ? <>
          确认不处理该条被举报的动态吗？<br />
          <Form ref={ref => this.processedFormRef = ref}>
            <Form.Item label="原因" name="remark" rules={[{ required: true }]} >
              <Input.TextArea bordered showCount maxLength={100} />
            </Form.Item>
          </Form>
        </> : <>
          {content}
        </>}
      </Modal>
    </div>)
  }
}

export default DynamicReport